package com.weiweiqin.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.weiweiqin.constants.EDASConstants;
import com.weiweiqin.utils.CompressPicUtil;
import com.weiweiqin.vo.common.Result;

/**
 * 
 * @author weiweiqin
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
	@ResponseBody
	public String upload(HttpServletRequest request,
			HttpServletResponse response) {
		Result result = new Result();
		Map<String, Object> mp = new HashMap<String, Object>();
		
		MultipartHttpServletRequest multipartHttpservletRequest = (MultipartHttpServletRequest) request;
		//Map<String, MultipartFile> fileMap = multipartHttpservletRequest.getFileMap();
		MultipartFile multipartFile = multipartHttpservletRequest
			.getFile("Filedata");
		String originalFileName = multipartFile.getOriginalFilename();

		String webapps = getTomcatWebappsPath(request);
		//原始图片存放路径
		String filePath = webapps + File.separator + EDASConstants.FileInfo.FILE_PATH;
		//压缩图片存放路径
		String compressFilePath = webapps +File.separator +EDASConstants.FileInfo.COMPRESS_FILE_PATH;
		System.out.println(filePath);
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		File compressFile = new File(compressFilePath);
		
		if (!compressFile.exists()) {
			compressFile.mkdirs();
		}
		String newFileName = System.currentTimeMillis()+"_"+originalFileName;
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(file + "/"
					+ newFileName);
			fileOutputStream.write(multipartFile.getBytes());
			fileOutputStream.flush();
			fileOutputStream.close();
			CompressPicUtil mypic = new CompressPicUtil();   
			mypic.compressPic(filePath+"/", compressFilePath+"/", newFileName, newFileName, 100, 100, true);  
		} catch (FileNotFoundException e) {
			result.setResult(false);
			result.setErrorMsg("没有找到图片文件");
			return result.toJson();
		} catch (IOException e) {
			result.setResult(false);
			result.setErrorMsg("上传图片失败...");
			return result.toJson();
		}
		result.setResult(true);
		mp.put("name", newFileName);
		mp.put("oriName", originalFileName);
		mp.put("size", multipartFile.getSize());
		result.setObj(mp);
		return result.toJson();
	}

	@RequestMapping("download.do")
	public void downloadFile(String fileName, HttpServletRequest request,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");

		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			String webapps = getTomcatWebappsPath(request);
			String filePath = webapps + File.separator + EDASConstants.FileInfo.FILE_PATH;
			File file = new File(fileName);
			System.out.println(file.getAbsolutePath());
			InputStream inputStream = new FileInputStream(filePath+"/" + file);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("downloadCompress.do")
	public void downloadCompress(String fileName, HttpServletRequest request,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");

		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			String webapps = getTomcatWebappsPath(request);
			String filePath = webapps +File.separator+ EDASConstants.FileInfo.COMPRESS_FILE_PATH;
			File file = new File(fileName);
			System.out.println(file.getAbsolutePath());
			InputStream inputStream = new FileInputStream(filePath+"/" + file);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取tomcat webapps目录
	 * 
	 * @param request
	 * @return
	 */
	private static String getTomcatWebappsPath(HttpServletRequest request) {
		String result = "";
		String tomcatRoot = request.getSession().getServletContext()
				.getRealPath("/");
		int indexOf = tomcatRoot.indexOf("webapps");
		if (indexOf != -1) {
			result = tomcatRoot.substring(0, indexOf + 7);
		}
		return result;
	}
	
	
}